<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>「パクリだ」と言われたデミアン・ハーストの作品をSchemeでパクってみるをJavaScriptでパクってみる</title>

<script type="text/javascript">
// <![CDATA[

//キャンバス要素のコンテキスト
var ctx = null;
var PI2 = Math.PI * 2;
var phi = (1 + Math.sqrt(5)) / 2;
var golden_angle = PI2 / Math.pow(phi,2);
var colors = [[46,139,87],[200,70,51],[255,140,10],[20,206,209],
              [240,240,100],[240,200,10],[106,90,205],[75,10,130],
              [192,192,192],[210,180,140],[240,192,203]];

function getRandomInt(min, max)
{
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

function clamp(x,a,b) {
  return Math.min(Math.max(x,a),b);
}

function make_color() {
  return colors[getRandomInt(0,colors.length-1)].map(function(x) {
    return clamp(x + getRandomInt(-5,5),0,255);
  });
}

function fermat_spiral(c,theta,n) {
  var r = 0, t = 0;
  var x, y;
  for (var i = 0; i < n; i++) {
    r = c * Math.sqrt(i);
    t = i * theta;
    x = 256 + r * Math.cos(t);
    y = 256 + r * Math.sin(t);
    ctx.beginPath();
    ctx.fillStyle = "rgb(" + make_color().join(",") + ")";
    ctx.moveTo(x,y);
    ctx.arc(x, y, 5, 0, PI2, false);
    ctx.fill();
  };
}

function main() {
  var canvas = document.getElementById("canvas");
  if (!canvas.getContext) return;
  ctx = canvas.getContext('2d');
  ctx.clearRect(0,0,512,512);
  var c = parseInt(document.getElementById("c").value,10);
  var theta = parseFloat(document.getElementById("theta").value);
  var n = parseInt(document.getElementById("n").value,10);
  if(isNaN(c)) c = 8;
  if(isNaN(theta)) theta = golden_angle;
  if(isNaN(n)) n = 1000;
  fermat_spiral(c,theta,n);
  return false;
}

window.onload = main;
// ]]>
</script>
</head>
<body>
<canvas id="canvas" width=512 height=512></canvas>
<form onsubmit="return main()">
  c = <input type="text" id="c" value="8"></input><br/>
  theta = <input type="text" id="theta" value="137.508"></input><br/>
  n = <input type="text" id="n" value="1000"></input><br/>
  <input type="submit" value="draw"></input>
</form>
</body>
</html>
